<?php

namespace app\admin\controller\facrm;

use addons\facrm\model\Admin as AdminModel;
use app\admin\model\AdminLog;
use app\common\controller\Backend;

use addons\third\library\Application;
use addons\third\library\Service;
use addons\third\model\Third as ThirdModel;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Lang;
use think\Session;

/**
 * 绑定微信公众号
 * @internal
 */
class Third extends Backend
{
    protected $app = null;
    protected $options = [];
    protected $noNeedRight = ['*'];
    const GET_AUTH_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('third');
        $this->app = new Application($config);
    }
    /**
     * 发起授权
     */
    public function connect()
    {
        $platform = 'wechat';
        $config = get_addon_config('third');
        if (!$config['status']) {
            $this->error("第三方登录已关闭");
        }


        $url = url('admin/facrm.third/callback','','',true);
        if (!$this->app->{$platform}) {
            $this->error('参数错误');
        }

        if ($url) {
            Session::set("redirecturl", $url);
        }

        $state = md5(uniqid(rand(), true));
        Session::set('state', $state);
        $queryarr = array(
            "appid"         => $config['wechat']['app_id'],
            "redirect_uri"  => $url,
            "response_type" => "code",
            "scope"         => $config['wechat']['scope'],
            "state"         => $state,
        );
        request()->isMobile() && $queryarr['display'] = 'mobile';
        $url = self::GET_AUTH_CODE_URL . '?' . http_build_query($queryarr) . '#wechat_redirect';
        // 跳转到登录授权页面
        $this->redirect($url);
        return;
    }

    /**
     * 通知回调
     */
    public function callback()
    {

        $platform='admin_mp';
        $model = new AdminModel();
        $get = $this->request->get();
        $third = get_addon_info('third');
        if (!$third || $third['state']!=1) {
            return $this->error(__("请先安装第三方登录插件"));
        }
        $data = $model->mpLogin($get);
        if (!$data) {
            return $this->error($model->getError());
        }
        if (!isset($data['original']['openid'])){
            return $this->error(__("获取微信登录信息失败"));
        }

        $data_param['openid'] = $data['original']['openid'];
        $data_param['unionId'] =isset($data['original']['unionId'])? $data['original']['unionId']:'';
        $data_param['expires_in'] =3600;
        $data_param['userinfo']['nickname'] = $data['nickname'];
        $data_param['userinfo']['avatar'] = $data['avatar'];
        $data_param['access_token'] = $data['access_token'];
        $data_param['refresh_token'] = $data['refresh_token'];
        $data_param['user_id'] = $this->auth->id;

        $third = $model->connects($platform, $data_param);

        AdminLog::setTitle(__('公众号绑定'));
        if ($third) {
            if (isset($third->user_id)&&$third->user_id) {
               $this->success("成功绑定，请关闭当前页面",url('admin/index/index'));
            } else {
                //绑定帐号
                $this->error(__("绑定失败，请重试",url('admin/index/index')));
            }
        }
        return $this->error(__("绑定失败，请重试",url('admin/index/index')));


    }

    /**
     * 解绑账号
     */
    public function unbind()
    {

        $platform = $this->request->request('platform','admin_mp');

        $third = \addons\third\model\Third::where('user_id', $this->auth->id)->where('platform', $platform)->find();
        if (!$third) {
            $this->error(__('绑定的数据不存在'));
        }
        $third->delete();
        return $this->success(__("解绑成功！"));
    }

}
